package me.zhengjie.utils;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class ExcelTemplateUtils {
    /**
     * 从resources目录导出Excel模板
     * @param response HttpServletResponse
     * @param templatePath 模板路径（相对于resources目录）
     * @param exportFileName 导出的文件名（不含扩展名）
     * @throws IOException
     */
    public static void exportFromTemplate(HttpServletResponse response,
                                          String templatePath,
                                          String exportFileName) throws IOException {
        // 加载资源文件
        Resource resource = new ClassPathResource(templatePath);
        if (!resource.exists()) {
            throw new RuntimeException("模板文件不存在: " + templatePath);
        }

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        String encodedFileName = URLEncoder.encode(exportFileName, String.valueOf(StandardCharsets.UTF_8))
                .replaceAll("\\+", "%20");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                "attachment;filename*=utf-8''" + encodedFileName + ".xlsx");

        // 将模板文件写入响应流
        try (InputStream inputStream = resource.getInputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                response.getOutputStream().write(buffer, 0, bytesRead);
            }
            response.getOutputStream().flush();
        }
    }

    /**
     * 适用于返回ResponseEntity的控制器方法
     */
    public static ResponseEntity<Resource> exportFromTemplate(String templatePath,
                                                              String exportFileName) throws IOException {
        Resource resource = new ClassPathResource(templatePath);
        if (!resource.exists()) {
            throw new RuntimeException("模板文件不存在: " + templatePath);
        }

        String encodedFileName = URLEncoder.encode(exportFileName, String.valueOf(StandardCharsets.UTF_8))
                .replaceAll("\\+", "%20");

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                .header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment;filename*=utf-8''" + encodedFileName + ".xlsx")
                .body(resource);
    }

}
